import axios from 'axios'
import Cookies from 'js-cookie'

axios.defaults.baseURL = 'http://localhost:3000'
axios.defaults.withCredentials = true

// 键值对的数据结构
const pendingRequest = new Map()

// 拿到方式和url
function generateReqKey (config) {
  const { method, url } = config
  return [method, url].join('&')
}

function addPendingRequest (config) {
  const requestKey = generateReqKey(config)
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken(cancel => {
      if (!pendingRequest.has(requestKey)) {
        pendingRequest.set(requestKey, cancel)
      }
    })
}

function removePendingRequest (config) {
  const requestKey = generateReqKey(config)
  if (pendingRequest.has(requestKey)) {
    const cancel = pendingRequest.get(requestKey)
    cancel(requestKey)
    pendingRequest.delete(requestKey)
  }
}

// 请求拦截器
axios.interceptors.request.use(
  function (config) {
    removePendingRequest(config) // 检查是否存在重复请求，若存在则取消已发的请求
    addPendingRequest(config) // 把当前请求添加到pendingRequest对象中
    return config
  },
  Cookies.get('cookie'),

  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(({ data }) => {
  return data
})

export default axios
